<template>
    <view class="container">
        <div class="border">
            <div class="border-content">
                <div style="height: 10px;"></div>
                <div class="top-line">
                    <div class="line"></div>
                    <div style="width: 10px;"></div>
                    <div style="color: #1A512C;" v-show="indent == '维保'">维保工单</div>
                    <div style="color: #1A512C;" v-show="indent == '巡检'">巡检工单</div>
                </div>
                <div style="height: 10rpx;"></div>
                <div style="display: flex;align-items: center;">
                    <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">派单时间</div>
                        <div class="borders">
                            <!-- <picker mode="date" :value="date" :start="startDate" :end="endDate" fields="day" @change="bindDateChange"> -->
                            <div style="height: 5rpx;"></div>
                            {{ obj.launchTime ?? obj.createTime ?? '暂无' }}
                            <div style="height: 5rpx;"></div>
                            <!-- </picker> -->

                        </div>
                    </div>
                </div>
                <div style="height: 10rpx;"></div>
                <!-- 表单 -->
                <div v-show="indent == '维保'" style="color: #718778;">
                    <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">派单类型</div>
                        <div class="borders">
                            <!-- <picker mode="date" :value="date" :start="startDate" :end="endDate" fields="day" @change="bindDateChange"> -->
                            <div style="height: 5rpx;"></div>
                            {{ obj.repairMaintainOrderState == 0 ? '自派单' : obj.repairMaintainOrderState == 1 ? "手工单" :
                                '' }}
                            <div style="height: 5rpx;"></div>
                            <!-- </picker> -->

                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">设备名称</div>
                        <div class="borders">
                            <!-- <picker mode="date" :value="date" :start="startDate" :end="endDate" fields="day" @change="bindDateChange"> -->
                            <div style="height: 5rpx;"></div>
                            {{ obj.deviceName }}
                            <div style="height: 5rpx;"></div>
                            <!-- </picker> -->

                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">设备编号</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            {{ obj.deviceNo }}
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">所属部门</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            {{ obj.deptName }}
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">紧急程度</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            {{ obj.emerDegree }}
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">故障类型</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            {{ obj.faultType }}
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">指定人员</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            {{ obj.userName }}
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">设备状态</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            {{ obj.deviceSate == 0 ? '正常' : obj.deviceSate == 1 ? '停用' : '' }}
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div class="form-flex" style="align-items: flex-start;">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">任务描述</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            <u--textarea disabled v-model="obj.taskDesc"></u--textarea>
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <u-line></u-line>
                    <div style="height: 10px;"></div>
                    <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">设备状态</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            {{ obj.deviceSate == 0 ? '正常' : obj.deviceSate == 1 ? '停用' : '' }}
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                </div>
                <div v-show="indent == '巡检'" style="color: #718778;">
                    <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">接单人员</div>
                        <div class="borders">
                            <!-- <picker mode="date" :value="date" :start="startDate" :end="endDate" fields="day" @change="bindDateChange"> -->
                            <div style="height: 5rpx;"></div>
                            {{ obj.orderPersonName }}
                            <div style="height: 5rpx;"></div>
                            <!-- </picker> -->

                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">巡检地点</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            {{ obj.inspectName }}
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div class="form-flex">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">巡检内容</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            {{ obj.inspectContent }}
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div style="height: 10px;"></div>
                    <div class="form-flex" style="align-items: flex-start;">
                        <div style="width: 30%;color: #1A512C;font-weight: 500;">任务描述</div>
                        <div class="borders">
                            <div style="height: 5rpx;"></div>
                            <u--textarea disabled v-model="obj.taskDescription"></u--textarea>
                            <div style="height: 5rpx;"></div>
                        </div>
                    </div>
                    <div style="height: 20px;"></div>
                    <u-line></u-line>
                    <div style="height: 10px;"></div>
                </div>
                <div v-if="obj.repairMaintainState == 1">
                    <div style="width: 30%;color: #1A512C;font-weight: 500;">照片</div>
                    <div style="height: 15px;"></div>
                    <div style="display: flex;align-items: center;justify-content: space-around;">
                        <div>
                            <u-upload :capture="['camera']" :fileList="fileList1" @afterRead="afterRead"
                                @delete="deletePic" name="1" multiple :maxCount="1" width="170" height="150">
                                <image src="https://28-1325662301.cos.ap-shanghai.myqcloud.com/static%2Fupload.jpg"
                                    mode="widthFix" style="width: 150px;height: 150px;"></image>
                            </u-upload>
                        </div>
                        <div>
                            <u-upload :capture="['camera']" :fileList="fileList2" @afterRead="afterReads"
                                @delete="deletePics" name="2" multiple :maxCount="1" width="170" height="150">
                                <image src="https://28-1325662301.cos.ap-shanghai.myqcloud.com/static%2Fupload.jpg"
                                    mode="widthFix" style="width: 150px;height: 150px;"></image>
                            </u-upload>
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                </div>
                <div v-if="obj.repairMaintainState == 1">
                    <div v-for="(item, index) in arr" style="margin-top: 10px;">
                        <div style="display: flex;align-items: center;">
                            <div class="borders" style="width: 70%;">
                                <div style="height: 5rpx;"></div>
                                <picker @change="(event) => bindChangeDevice(event, index)" :value="index"
                                    :range="deList">
                                    <input type="text" v-model="item.partName" placeholder="选择设备" disabled>
                                </picker>
                                <div style="height: 5rpx;"></div>
                            </div>
                            <div style="width: 1%;"></div>
                            <div class="borders" style="width: 20%;">
                                <div style="height: 5rpx;"></div>
                                <input type="number" placeholder="数量" v-model="item.exitQuantity">
                                <div style="height: 5rpx;"></div>
                            </div>
                        </div>
                    </div>
                    <div style="height: 10px;"></div>
                    <div class="addImg" style="display: flex; align-items: center; justify-content: center"
                        @click="pushArr">
                        <image src="https://28-1325662301.cos.ap-shanghai.myqcloud.com/static%2Fadd.png"
                            mode="widthFix" />
                        <div style="width: 10rpx"></div>
                        <div>新增备件</div>
                    </div>
                </div>
                <!-- 按钮 -->
                <div style="height: 10px;"></div>
                <div v-show="indent == '维保'" class="footer">
                    <div class="button-footers" v-if="obj.repairMaintainState === 0" @click="cancel">取消</div>
                    <div class="button-footer" v-if="obj.repairMaintainState === 0" @click="acceptTask">接受</div>
                    <div class="button-footer" style="width: 100%;" v-if="obj.repairMaintainState == 1" @click="doneWb">
                        完成
                    </div>
                </div>
                <div v-show="indent == '巡检'" class="footer">
                    <div class="button-footers" style="width: 45%;" v-if="obj.workOrderState == 1" @click="cancelOrd">
                        取消任务
                    </div>
                    <div class="button-footer" style="width: 45%;" v-if="obj.workOrderState == 1" @click="jiedanXj">接单
                    </div>
                    <div class="button-footer" v-if="obj.workOrderState == 2" style="width: 45%;" @click="scan">扫码</div>
                    <div class="button-footer" v-if="obj.workOrderState == 2" style="width: 45%;" @click="NFC">NFC</div>
                </div>
                <div style="height: 10px;"></div>

            </div>
        </div>
    </view>
</template>
<script>
import request from '../../common/request';
import { scanCode,partList, getMaintainDetail, acceptWb, getInspectOrderDetail, delInspectOrder, doneWbTask, acceptXj } from '../api/api.js';
export default {
    data() {
        const currentDate = this.getDate({
            format: true
        })
        return {
            date: currentDate,
            indent: '',
            obj: {},
            fileList1: [],
            fileList2: [],
            base: '',
            request: request,
            img1: '',
            img2: '',
            arr: [
                {
                    partId: '', //备件id
                    partName: '', //备件名
                    exitQuantity: '', //使用数量
                    quantityUnit: '', //单位
                    exitReason: '', //出库原因：损坏、过期、退换、维保
                    exitDesc: '' //出库描述
                }
            ],
            deList: [],
            seaDeList: []
        }
    },
    methods: {
        //扫码
        scan() {
            let t = this;
            uni.authorize({
                scope: 'scope.camera',
                success() {
                    // 用户同意授权
                    t.scanQRCode();
                },
                fail() {
                    // 用户拒绝授权
                    uni.showToast({
                        title: '您拒绝了授权',
                        icon: 'none'
                    });
                }
            });


        },
        scanQRCode(){
            let t = this;
            uni.scanCode({
        success(res) {
            if (res.result) {
                // 扫描成功，处理二维码内容
                console.log('扫描结果：', res.result);
                // 这里可以进行后续操作，如跳转页面、显示信息等
                scanCode({
                    UUID:res.result,
                    ID:t.obj.id
                }).then(res=>{
                    console.log(res.data,'scanCode->SUCCESS');
                    if(res.data.code==200){
                        uni.showToast({
                            title:res.data.msg,
                            icon:'success'
                        })
                        setTimeout(()=>{
                            uni.navigateBack({
                                delta:1
                            })
                        },1000)
                    }else{
                        uni.showToast({
                            title:res.data.msg,
                            icon:'none'
                        })
                    }
                })
            } else {
                // 扫描失败
                uni.showToast({
                    title: '扫描失败',
                    icon: 'none'
                });
            }
        },
        fail() {
            // 调用相机失败
            uni.showToast({
                title: '调用相机失败',
                icon: 'none'
            });
        }
    });
        },
        pushArr() {
            this.arr.push(
                {
                    partId: '', //备件id
                    partName: '', //备件名
                    exitQuantity: '', //使用数量
                    quantityUnit: '', //单位
                    exitReason: '', //出库原因：损坏、过期、退换、维保
                    exitDesc: '' //出库描述
                }
            )
        },
        //选择设备
        bindChangeDevice(e, index) {
            console.log(e.detail.value, index);
            const value = e.detail.value;
            this.arr[index].partId = this.seaDeList[value].id;
            this.arr[index].partName = this.seaDeList[value].partName;
            this.arr[index].quantityUnit = this.seaDeList[value].quantityUnit;
            // this.arr[index].exitReason = this.seaDeList[value].id;
            // this.arr[index].partId = this.seaDeList[value].id;
        },
        //接受维保
        acceptTask() {
            let t = this;
            uni.showModal({
                title: '提示',
                content: '确认接受当前任务吗',
                success: function (res) {
                    if (res.confirm) {
                        acceptWb(t.obj.id).then(res => {
                            console.log(res.data, 'res.data');
                            if (res.data.code == 200) {
                                uni.showToast({
                                    title: res.data.msg,
                                    duration: 2000,
                                    icon: 'none'
                                });
                                setTimeout(() => {
                                    uni.navigateBack({ delta: 1 })
                                }, 1000)
                            }
                        })
                    } else if (res.cancel) {
                        uni.showToast({
                            title: '取消',
                            duration: 2000,
                            icon: 'none'
                        });
                    }
                }
            });

        },
        // 返回
        cancelOrd() {
            let t = this;
            uni.showModal({
                title: '提示',
                content: '确认取消当前任务吗',
                success: function (res) {
                    if (res.confirm) {
                        delInspectOrder(t.obj.id).then(res => {
                            console.log(res.data, 'res.data');
                            if (res.data.code == 200) {
                                uni.showToast({
                                    title: res.data.msg,
                                    duration: 2000,
                                    icon: 'none'
                                });
                                setTimeout(() => {
                                    uni.navigateBack({ delta: 1 })
                                }, 1000)
                            } else {
                                uni.showToast({
                                    title: res.data.msg,
                                    duration: 2000,
                                    icon: 'none'
                                });
                            }
                        })
                    } else if (res.cancel) {
                        uni.showToast({
                            title: '取消',
                            duration: 2000,
                            icon: 'none'
                        });
                    }
                }
            });
        },
        bindDateChange: function (e) { //选择日期
            this.date = e.detail.value
            console.log('date', this.date)
        },
        getDate(type) { //年月日
            const date = new Date();
            // const date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();

            if (type === 'start') {
                year = year - 60;
            } else if (type === 'end') {
                year = year + 2;
            }
            month = month > 9 ? month : '0' + month;
            day = day > 9 ? day : '0' + day;
            return `${year}-${month}-${day}`;
        },
        deletePic(event) {
            this[`fileList${event.name}`].splice(event.index, 1)
        },
        deletePics(event) {
            this[`fileList${event.name}`].splice(event.index, 1)
        },
        // 新增图片
        async afterRead(event) {
            console.log(event);
            let lists = [].concat(event.file)
            let fileListLen = this[`fileList${event.name}`].length
            lists.map((item) => {
                this[`fileList${event.name}`].push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                })
            })
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url)
                let item = this[`fileList${event.name}`][fileListLen]
                this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                    status: 'success',
                    message: '',
                    url: result
                }))
                fileListLen++
            }
        },
        async afterReads(event) {
            console.log(event);
            let lists = [].concat(event.file)
            let fileListLen = this[`fileList${event.name}`].length
            lists.map((item) => {
                this[`fileList${event.name}`].push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                })
            })
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromises(lists[i].url)
                let item = this[`fileList${event.name}`][fileListLen]
                this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                    status: 'success',
                    message: '',
                    url: result
                }))
                fileListLen++
            }
        },
        uploadFilePromise(url) {
            return new Promise((resolve, reject) => {
                let a = uni.uploadFile({
                    url: `${this.base}/file-upload/single`,
                    filePath: url,
                    name: 'file',
                    formData: {
                        'type': 'faultPhoto'
                    },
                    header: {
                        Authorization: uni.getStorageSync('token')
                    },
                    success: (res) => {
                        const data = JSON.parse(res.data)
                        console.log(data);
                        this.img1 = data.data;
                        resolve(res.data.data)
                    }
                });
            })
        },
        uploadFilePromises(url) {
            return new Promise((resolve, reject) => {
                let a = uni.uploadFile({
                    url: `${this.base}/file-upload/single`,
                    filePath: url,
                    name: 'file',
                    formData: {
                        'type': 'faultPhoto'
                    },
                    header: {
                        Authorization: uni.getStorageSync('token')
                    },
                    success: (res) => {
                        const data = JSON.parse(res.data)
                        console.log(data, 'data2');
                        this.img2 = data.data;
                        resolve(res.data.data)
                    }
                });
            })
        },
        doneWb() {
            if (this.img1 == '' || this.img2 == '') {
                uni.showToast({
                    title: '请输入完整',
                    icon: 'none'
                });
            } else {
                let combinedString = `${this.img1},${this.img2}`;
                doneWbTask({
                    id: this.obj.id,
                    scenePhoto: combinedString,
                    partExitList: this.arr
                }).then(res => {
                    console.log(res.data, 'res.data');
                    if (res.data.code == 200) {
                        uni.showToast({
                            title: res.data.msg,
                            icon: 'none'
                        });
                        setTimeout(() => {
                            this.img1 = '';
                            this.img2 = '';
                            this.fileList1 = [];
                            this.fileList2 = [];
                            uni.navigateBack({
                                delta: 1
                            });
                        }, 1000)
                    }
                })
            }

        },
        jiedanXj() {
            let t = this;
            uni.showModal({
                title: '提示',
                content: '确认接受当前任务吗',
                success: function (res) {
                    if (res.confirm) {
                        acceptXj(t.obj.id).then(res => {
                            console.log(res.data, 'res.data');
                            if (res.data.code == 200) {
                                uni.showToast({
                                    title: res.data.msg,
                                    duration: 2000,
                                    icon: 'none'
                                });
                                setTimeout(() => {
                                    uni.navigateBack({ delta: 1 })
                                }, 1000)
                            }
                        })
                    } else if (res.cancel) {
                        uni.showToast({
                            title: '取消',
                            duration: 2000,
                            icon: 'none'
                        });
                    }
                }
            });
        },
        //维保工单
        // getWb(){
        //     uni.showLoading({
        //             title: '加载中',
        //             mask:true
        //         });
        //     mainList({
        //         repairMaintainState:'1',
        //         type:'2'
        //     }).then(res=>{
        //         console.log(res.data.rows[0].repairMaintainTask);
        //         this.obj = res.data.rows[0].repairMaintainTask;
        //         if(this.obj){
        //             uni.hideLoading();
        //         }
        //     }).catch(err=>{
        //         console.error(err,'err')
        //         uni.showToast({
        //                 title:'暂无工单',
        //                 icon:'none'
        //             })
        //         setTimeout(()=>{
        //             uni.navigateBack({delta:1})
        //         },1000)
        //     })
        // },
        // getXj(){
        //     insList({
        //         workOrderState:'1'
        //     }).then(res=>{
        //         console.log(res.data);
        //         this.obj = res.data.data[0];
        //     })
        // }
        NFC() {
            console.log(13);


        },
        getDevice() {
            partList({}).then(res => {
                console.log(res.data, 'res.data123');
                this.deList = res.data.rows.map((item) => `${item.partName}(${item.bomNo})`);
                this.seaDeList = res.data.rows;
            })
        }
    },
    computed: {
        startDate() {
            return this.getDate('start');
        },
        endDate() {
            return this.getDate('end');
        }
    },
    onLoad(options) {
        this.indent = uni.getStorageSync('pageIndent');
        if (this.indent == '维保') {
            getMaintainDetail(options.id).then(res => {
                console.log(res.data, 'res.data');
                this.obj = res.data.data;
            })
        } else if (this.indent == '巡检') {
            getInspectOrderDetail(options.id).then(res => {
                console.log(res.data, '巡检--->res.data');
                this.obj = res.data.data;
                console.log(this.obj,'obj');
                
            })
        }


    },
    onShow() {
        this.base = this.request.config.baseURL;
        this.getDevice();
    }
}
</script>
<style lang="scss">
.container {
    background: #394E36;

    .border {
        border-radius: 10px;
        background: #E3EDE2;
        height: 100vh;
        overflow-y: scroll;

        .border-content {
            width: 90%;
            margin-left: 5%;
        }
    }
}

.top-line {
    display: flex;
    align-items: center;
}

.line {
    background: #1A512C;
    width: 7rpx;
    height: 35rpx;
}

.form-flex {
    display: flex;
    align-items: center;
    width: 100%;
}

.borders {
    border: 1px solid #1A512C;
    border-radius: 5px;
    text-align: center;
    width: 70%;
}

.borders-min {
    border: 1px solid #1A512C;
    border-radius: 5px;
    text-align: center;
}

.footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.button-footer {
    width: 48%;
    height: 50px;
    background: #46A164;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 18px;
    font-weight: 500;
    border-radius: 10px;
}

.button-footers {
    width: 48%;
    height: 50px;
    background: #C34843;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 18px;
    font-weight: 500;
    border-radius: 10px;
}

.addImg image {
    width: 50rpx;
    height: 50rpx;
}
</style>